from PyQt4 import QtCore, QtGui
import sys
from scene import *
from view import *
from accident import *


class MainWindow(QtGui.QMainWindow):
    interval = 40

    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.scene = BricksScene(self)
        self.resize(410, 340)
        self.createBricks()
        self.resetBricks()
        self.view = BricksView(self.scene, self)
        self.view.setRenderHint(QtGui.QPainter.Antialiasing)
        self.view.setScene(self.scene)
        self.view.setFocusPolicy(QtCore.Qt.NoFocus)
        self.view.resize(370, 280)
        self.view.move(20, 20)
        self.createBricks()
        self.connect(sender, QtCore.SIGNAL('gameOver()'), self.endGame)
        self.run = False
        self.view.show()
        self.startTimer(self.interval)

    def keyPressEvent(self, event):
        if not self.run:
            return
        # print(event.key())
        if event.key() == QtCore.Qt.Key_Up:
            self.userBrick.setPos(self.userBrick.xPos, self.userBrick.yPos - 10)
        elif event.key() == QtCore.Qt.Key_Down:
            self.userBrick.setPos(self.userBrick.xPos, self.userBrick.yPos + 10)
        elif event.key() == QtCore.Qt.Key_Left:
            self.userBrick.setPos(self.userBrick.xPos - 10, self.userBrick.yPos)
        elif event.key() == QtCore.Qt.Key_Right:
            self.userBrick.setPos(self.userBrick.xPos + 10, self.userBrick.yPos)


    def createBricks(self):
        self.bricks = list()
        for i in range(2):
            self.bricks.append(Brick(i+1))
            self.scene.addItem(self.bricks[i])
        self.userBrick = UserBrick(0)
        self.scene.addItem(self.userBrick)

    def resetBricks(self):
        # self.bricks[0].setRect(5, 5, 20, 20)
        # self.bricks[0].setForward(1, 1)
        # self.bricks[1].setRect(100, 5, 20, 20)
        # self.bricks[1].setForward(0, 1)
        # self.bricks[2].setRect(5, 100, 20, 20)
        # self.bricks[2].setForward(0, 1)
        # self.bricks[3].setRect(0, 20, 20, 20)
        # self.bricks[3].setForward(1, 0)
        self.userBrick.brickType = 0
        self.userBrick.setRect(145, 110, 20, 20)

    def startGame(self):
        self.resetBricks()
        self.run = True

    def endGame(self):
        # self.run = False
        print('game over')

    def timerEvent(self, event):
        if not self.run:
            return
        handleAccident(self.bricks)
        updatePos(self.bricks)

